package com.heima.search.service.Impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Override
    public void insert(String keyword, Integer userId) {
        //1.根据关键词查询搜索历史记录
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //2.判断是否存在
        if (userSearch != null){
            //2.1存在跟新时间
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        //3不存在新增
        //3.1封装新数据对象
        userSearch.setCreatedTime(new Date());
        userSearch.setKeyword(keyword);
        userSearch.setUserId(userId);
        //3.2查询用户搜索记录列表
        Query query1 = Query.query(Criteria.where("userId").is(userId)).with(Sort.by("createdTime").descending());
        List<ApUserSearch> userSearchList = mongoTemplate.find(query1, ApUserSearch.class);
        //3.3判断数据是否超过10条(替换掉最后一条)
        if (userSearchList != null && userSearchList.size()>=10){
            ApUserSearch apUserSearchLast = userSearchList.get(userSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(apUserSearchLast.getId())),userSearch);
            return;
        }

        //3.4数量不大于10，直接保存
        mongoTemplate.save(userSearch);
    }

    /**
     * 加载搜索记录列表
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //1.获取当前用户
        ApUser apUser = AppThreadLocalUtil.getUser();

        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.查询当前用户的搜索记录列表
        Query query = new Query(Criteria.where("userId").is(apUser.getId())).with(Sort.by("createdTime").descending());
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(apUserSearches);

    }

    /**
     * 删除搜索记录
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        //1.校验参数
        if (historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.判断用户是否登录
         ApUser apUser = AppThreadLocalUtil.getUser();
        if (AppThreadLocalUtil.getUser() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.根据用户id和历史记录id删除记录
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(apUser.getId())
                .and("id").is(historySearchDto.getId())),ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
